package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.common.PaginationVO;
import com.itheima.entity.YddTag;
import com.itheima.exception.BusinessException;
import com.itheima.mapper.TagMapper;
import com.itheima.vo.TagVO;
import com.itheima.service.TagService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class TagServiceImpl implements TagService {
    private final TagMapper tagMapper;

    @Override
    public List<YddTag> getAll() {
        List<YddTag> tagList = tagMapper.getAll();
        return tagList;
    }

    @Override
    public PaginationVO<YddTag> page(String page, String limit, String tagname) {
        PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(limit));
        List<TagVO> tags = tagMapper.list(tagname);
        System.out.println(tags);
        PageInfo<TagVO> pageInfo = new PageInfo<>(tags);
        long count = pageInfo.getTotal();
        int totalPages = pageInfo.getPages();
        int pageSize = pageInfo.getPageSize();
        int currentPage = pageInfo.getNextPage();
        List<TagVO> sysTagList = pageInfo.getList();

        List<YddTag> tagVOList = new ArrayList<>();
        sysTagList.forEach(yddTag -> tagVOList.add(yddTag.getYddTag()));
        System.out.println(tagVOList);
        PaginationVO<YddTag> paginationVO = new PaginationVO<>();
        paginationVO.setCount(count);
        paginationVO.setTotalPages(totalPages);
        paginationVO.setPageSize(pageSize);
        paginationVO.setCurrentPage(currentPage);
        paginationVO.setData(tagVOList);
        System.out.println(paginationVO);
        return paginationVO;
    }

    @Override
    public void deleteById(String id) {
        tagMapper.deleteById(id);
    }

    @Override
    public void addTag(YddTag tag) {
        Integer count = tagMapper.getTagCount(tag.getTagname());
        if (count > 0) {
            throw new BusinessException("名字已经存在！");
        }
        tagMapper.addTag(tag);
    }

    @Override
    public void updateTag(YddTag tag) {
        Integer count = tagMapper.getTagCounts(tag.getTagname(),tag.getId());
        if (count > 0) {
            throw new BusinessException("名字已经存在！");
        }
        tagMapper.updateTag(tag);
    }

    @Override
    public YddTag rowInfoById(String id) {
        YddTag tag = tagMapper.rowInfoById(id);
        return tag;
    }
}
